import os
import sys, getopt
from xml.dom.minidom import parse

import pypinyin


def readXML(filePath):
    print("修改文件"+filePath)
    domTree = parse(filePath)
    # 文档根元素
    rootNode = domTree.documentElement
    demos = rootNode.getElementsByTagName("name")
    print(demos)
    for demo in demos:
        name = demo.childNodes[0].data
        demo.childNodes[0].data = name + "[" + pinyinWord(name) + "]"
        print(name)
        print(demo.childNodes[0].data)

    # for demo in demos:
    #     name = demo.getElementsByTagName("name")[0]
    #     print(name)
    #     print(name.childNodes[0].data)
    #     print(pinyinWord(name.childNodes[0].data))
    #     name.childNodes[0].data = name.childNodes[0].data + "[" + pinyinWord(name.childNodes[0].data) + "]"
    #
    # 写入修改
    with open(filePath, "w", encoding="utf-8") as fo:
        domTree.writexml(fo, indent='', encoding="utf-8")
        fo.close()


# 拼音首字母拼接
def pinyinWord(sting):
    print([i for i in pypinyin.lazy_pinyin(sting, style=pypinyin.FIRST_LETTER,  errors='default', strict=False)])
    return "".join([i for i in pypinyin.lazy_pinyin(sting, style=pypinyin.FIRST_LETTER,  errors='default', strict=False)])


def main():
    # 获取当前文件所在目录
    path = os.getcwd()
    # 得到文件夹下的所有文件名称
    files = os.listdir(path)
    for file in files:  # 遍历文件夹
        if not os.path.isdir(file) and os.path.splitext(file)[-1] == ".xml":  # 判断是否是文件夹和是否为.xml后缀名，不是才打开
            print("file: "+file)
            readXML(path + "/" + file)  # 修改参数
            # print(os.path.splitext(file)[-1])
            # f = open(path + "/" + file)  # 打开文件
            # iter_f = iter(f)  # 创建迭代器
            # str = ""
            # for line in iter_f:  # 遍历文件，一行行遍历，读取文本
            #     str = str + line
            # s.append(str)  # 每个文件的文本存到list中

    # print('参数列表:', str(sys.argv))
    # print('脚本名为：', sys.argv[0])
    # for i in range(1, len(sys.argv)):
    #     print('参数 %s 为：%s' % (i, sys.argv[i]))


if __name__ == "__main__":
    main()
